<template>
    <el-space>
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="startInsert('')"
        ></el-button>
        <el-input
            placeholder="请输入查询字符"
            clearable
            :prefix-icon="Search"
            v-model="searchPrefix"
        />
        <el-button type="primary" icon="Search" @click="search()"></el-button>
    </el-space>
    <el-table
        stripe
        :data="tableData"
        style="width: 100%">
        <el-table-column fixed prop="name" label="Name"/>
        <el-table-column prop="roles" label="roles"/>
        <!--    <el-table-column prop="city" label="City" width="120" />-->
        <!--    <el-table-column prop="address" label="Address" width="600" />-->
        <!--    <el-table-column prop="zip" label="Zip" width="120" />-->
        <el-table-column fixed="right" label="Operations">
            <template #default="scope">
                <el-button link type="primary" size="small" icon="Stamp" @click="startGrant(scope.row)"></el-button>
                <el-button link type="primary" size="small" icon="Delete" @click="startDelete(scope.row)"></el-button>
            </template>
        </el-table-column>
    </el-table>
    <el-dialog
        title="Add User"
        v-model="insertFormShow"
        width="500"
    >
        <el-form ref="insertFormRef" :model="insertForm" :rules="insertFormRules" :label-width="120" label-position="left">
            <el-form-item label="name" prop="name">
                <el-input v-model="insertForm.name" placeholder="请保证 name 唯一"/>
            </el-form-item>
            <el-form-item label="password" prop="password">
                <el-input v-model="insertForm.password" placeholder=""/>
            </el-form-item>
        </el-form>
        <template #footer>
            <div style="display: flex; justify-content: space-between; align-items: center;">
                <div>
                    <el-button @click="insertFormShow = false">取消</el-button>
                    <el-button type="primary" @click="confirmInsert">确定</el-button>
                </div>
            </div>
        </template>
    </el-dialog>
    <el-dialog
        title="用户授权"
        v-model="grantFormShow"
        width="500"
    >
        <el-form ref="grantFormRef" :model="grantForm" :rules="grantFormRules" :label-width="120" label-position="left">
            <el-form-item label="user" prop="user">
                <el-input :disabled="grantForm.userReadOnly" v-model="grantForm.user"
                          placeholder="请保证名称唯一, 否则会覆盖同名的链接信息"/>
            </el-form-item>
            <el-form-item label="role" prop="role">
                <el-input v-model="grantForm.role" placeholder="示例 http://192.168.0.1:8080"/>
            </el-form-item>
        </el-form>
        <template #footer>
            <el-space>
                <el-button @click="grantFormShow = false">取消</el-button>
                <el-button type="primary" @click="confirmGrant">确定</el-button>
            </el-space>
        </template>
    </el-dialog>
</template>

<script setup>
import {defineProps, onMounted, ref} from "vue";
import {ElMessage, ElMessageBox} from 'element-plus'
import {auth_user_grant,auth_authenticate, auth_user_list} from "@/api/etcd3.js"
import {Search} from "@element-plus/icons-vue";
import {auth_user_add, auth_user_delete, auth_user_get, lease_ttl} from "../../api/etcd3.js";
import {Base64} from "js-base64";

const props = defineProps({
    connect: {
        type: Object,
        default: {
            name: '默认标题',
            url: 'http://127.0.0.1:2379',
            version: 'v2',
            username: 'root',
            password: '123456'
        }
    }
})

const tableData = ref([
    {
        name: 'Tom',
        roles: ['California'],
    }
])

const handleClick = () => {
    console.log('click')
}

// 用户授权
const grantFormShow = ref(false);
const grantFormRef = ref(null)
const grantForm = ref({
    user: '',
    userReadOnly: false,
    role: ''
})

const grantFormRules = ref({
    user: [
        {required: true, message: 'Please input role', trigger: 'blur'},
        {min: 1, message: 'Length should be greater than 3', trigger: 'blur'},
    ],
    role: [
        {required: true, message: 'Please input role', trigger: 'blur'},
        {min: 1, message: 'Length should be greater than 3', trigger: 'blur'},
    ],
})

function startGrant(row) {
    grantFormShow.value = true;
    grantForm.value.user = row.name;
    grantForm.value.userReadOnly = true;
    grantForm.value.role = '';
}

function confirmGrant() {
    grantFormRef.value.validate((valid) => {
        if (valid) {
            // 关闭弹框
            grantFormShow.value = false;
            // 执行新增逻辑
            let grant = {
                user: grantForm.value.user,
                role: grantForm.value.role,
            };

            let url = props.connect.url;
            auth_user_grant(url, grant)
                .then(res => {
                    ElMessage.success('auth_user_grant ' + 'success');
                    // 重新查询
                    search();
                })
                .catch(error => {
                    let message = error.response.data.message;
                    ElMessage.error('auth_user_grant ' + message);
                });

        }
    });
}

// 新增
const insertFormShow = ref(false);
const insertFormRef = ref(null)
const insertForm = ref({
    name: '',
    password:''
})
const insertFormRules = ref({
    name: [
        {required: true, message: 'Please input ID', trigger: 'blur'},
        {min: 1, message: 'Length should be greater than 1', trigger: 'blur'},
    ]
})
function startInsert(){
    insertFormShow.value = true;
    insertForm.value.name = null;
    insertForm.value.password = null;
}
function confirmInsert() {
    insertFormRef.value.validate((valid) => {
        if (valid) {
            // 关闭弹框
            insertFormShow.value = false;
            // 执行新增逻辑
            let url = props.connect.url;
            let name = insertForm.value.name;
            let password = insertForm.value.name;
            let hashedPassword = '';
            let data = {
                "name": name,
                "password": password
            };
            auth_user_add(url, data)
                .then(res => {
                    ElMessage.success('auth_user_add ' + 'success');
                    // 重新查询
                    search();
                })
                .catch(error => {
                    let message = error.response.data.message;
                    ElMessage.error('auth_user_add ' + message);
                });

        }
    });
}

// 删除
function startDelete(row) {
    ElMessageBox.confirm(
        'Permanently delete the node. Continue?',
        'Warning',
        {
            confirmButtonText: 'OK',
            cancelButtonText: 'Cancel',
            type: 'warning',
        }
    )
        .then(() => {
            confirmDelete(row);
        })
        .catch(() => {
            // do nothing
        })
}

function confirmDelete(row) {
    let url = props.connect.url;
    let name = row.name;
    auth_user_delete(url, name)
        .then(response => {
            search();
        })
        .catch(error => {
            let message = error.response.data.message;
            ElMessage.error('kv_delete ' + message);
        });
}

// 查询
const searchPrefix = ref(null)
function search(){
    let url = props.connect.url;
    auth_user_list(url)
        .then(res => {
            console.log(res);
            tableData.value = [];
            let users = [];
            let nodes = res.data.users;
            if (Array.isArray(nodes)) {
                for (let i = 0; i < nodes.length; i++) {
                    // nodes[i].hasChildren =false;
                    // nodes[i].children = []
                    let u = {};
                    u.name = nodes[i];
                    if(!!searchPrefix.value){
                        if(u.name.includes(searchPrefix.value)){
                            users.push(u);
                        }else{
                            continue;
                        }
                    }else{
                        users.push(u);
                    }
                }
                users.sort((a, b) => {
                    return a.name.localeCompare(b.name);
                });
                tableData.value = users;
            }
            searchRoles();
        })
        .catch(error => {
            let message = error.response.data.message;
            ElMessage.error('auth_user_list ' + message);
        })
}

//
function searchRoles(){
    let url = props.connect.url;
    if(tableData.value && Array.isArray(tableData.value)){
        for (let index = 0; index < tableData.value.length; index++) {
            let row = tableData.value[index];
            auth_user_get(url,row.name)
                .then(res=>{
                    let result = res.data;
                    let roles = [];
                    if(Array.isArray(result.roles)){
                        for (let i = 0; i < result.roles.length; i++) {
                            roles.push(result.roles[i]);
                        }
                    }
                    row.roles = roles;
                    console.log('tableData.value',tableData.value);
                })
                .catch(error=>{
                    let message = error.response.data.message;
                    ElMessage.error('auth_user_get ' + message);
                })
        }
    }
}

onMounted(() => {
    search();
})

</script>